package red.internal.server.registry.channel;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;

/**
 * @author Jin Zheng
 * @since 2020-07-19
 */
public class NotifyCache
{
	private static Logger logger = LoggerFactory.getLogger(NotifyCache.class);

	private final Cache<Long, NotifyCacheObject> cache;
	private static volatile NotifyCache instance;

	private NotifyCache()
	{
		this.cache = Caffeine.newBuilder()
				.expireAfterWrite(Duration.ofMinutes(10))
				.maximumSize(1000)
				.build();
	}

	public static NotifyCache getInstance()
	{
		if (instance == null)
		{
			synchronized (NotifyCache.class)
			{
				if (instance == null)
				{
					instance = new NotifyCache();
				}
			}
		}
		return instance;
	}

	public void add(NotifyCacheObject object)
	{
		cache.put(object.getMessageId(), object);
		if (logger.isDebugEnabled())
		{
			logger.debug("Add notify message, messageId: 0x{}", Long.toHexString(object.getMessageId()));
		}
	}

	public void remove(Long messageId)
	{
		cache.invalidate(messageId);
		if (logger.isDebugEnabled())
		{
			logger.debug("Remove notify message, messageId: 0x{}", Long.toHexString(messageId));
		}
	}

}
